const app = getApp();
import { ActivityRegistration_quxiao, activityOption, currentComment, comment, activitiesShoping_list, activitiesPlace_list, activitiesScspot_list, activityDetails, activityGive_option } from "../../../api/homePage"
import { getStorage } from "../../../utils/localStorage"
import { baseUrl } from "../../../api/request"
import { getMapDistance } from "../../../utils/address"
Page({
    data: {
        navData: {
            level: 2,
            title: 'banner详情'
        },
        imgUrl: baseUrl,
        scFlag: true,
        navHeight: 0,
        navTop: 0,
        navObj: 0,
        navWeight: 0,
        swiper: {
            autoplay: true, //自动切换
            dots: true, //指示点
            dotsColor: "#ffffff", //指示点颜色
            dotsActiveColor: "#4646A0", //选中指示点颜色
            circular: true, //衔接滑动
            duration: 3000, //滑动动画时长
            boxFlag: false,
        },
        mapConfig: {
            scale: 16, //缩放级别，取值范围为3-20
            minScale: 3, //最小缩放级别
            maxScale: 20, //最大缩放级别
            enable3D: true, //展示3D楼块
            enableZoom: false, //是否支持缩放
            enableScroll: false, //是否支持拖动
            enableBuilding: true, //是否展示建筑物
            tapFlag: true,
        },
        user: getStorage('user'),
        soFlag: false,
        detailObj: {},
        signFlag: null,
        content: "",
        latlng: {},
        productList: [], //相关产品列表
        placeList: [], //相关场所列表
        scenicspotList: [], //相关景区列表
        navMargin: app.globalData.navHeight + app.globalData.navTop,
    },
    onLoad(options) {
        //判断用户是否已经登录，否则跳转到登录页重新登录
        if (!getStorage("user")) {
            wx.redirectTo({
                url: '/pages/bootPage/index',
            });
        };
        /* 获取是否是从分享页进来的参数 true时 false不是 */
        app.globalData.sheetFlag = false;
        if (options.sheet) {
            app.globalData.sheetFlag = options.sheet;
        };
        //重置全局关于活动操作的全局变量
        app.globalData.activityId = null; //活动id
        app.globalData.activityGive = null; //活动点赞状态
        app.globalData.activityGiveNum = null; //活动点赞数量
        app.globalData.activityCtion = null; //活动收藏状态
        app.globalData.activityCtionNum = null; //活动收藏数量
        app.globalData.activityMent = null; //活动评论数量
        app.globalData.signUpNum = null; //活动报名人数
        const id = options.id;
        this.setData({
            imgUrl: baseUrl,
            user: getStorage('user'),
            latlng: getStorage('latLng'),
        });
        this.getActivityDetails(id);
    },
    onShow() {
        if (this.data.mydata != undefined) {
            app.globalData.signUpNum = this.data.mydata.peopleNumber;
            this.setData({
                "detailObj.peopleNumber": this.data.mydata.peopleNumber,
                "detailObj.signUpState": this.data.mydata.signUpState,
            });
            console.log(this.data.mydata,'mydata');
        };
    },
    //获取活动详情数据
    getActivityDetails(id) {
        activityDetails({ userId: this.data.user.id, activityId: id }).then(res => {
            res.data.data.imageScale = res.data.data.imageScale.split(",");
            res.data.data.latlng = res.data.data.longitude + "," + res.data.data.latitude;
            res.data.data.distance = getMapDistance(this.data.latlng.lat, this.data.latlng.lng, res.data.data.latitude, res.data.data.longitude);
            this.setData({
                "navData.title": res.data.data.title,
                detailObj: res.data.data
            });
            app.globalData.activityId = this.data.detailObj.id;  //全局变量活动id
            app.globalData.signUpNum = this.data.detailObj.peopleNumber;  //全局变量活动报名人数
            this.getList();
            this.getProductList();
            this.getPlaceList();
            this.getScenicspotList();
        });
    },
    //获取相关商品列表
    getProductList() {
        let that = this.data;
        activitiesShoping_list({ activityId: this.data.detailObj.id }).then(res => {
            if (!res.data.data || res.data.data.length === 0) {
                this.setData({
                    productList: []
                });
            } else {
                res.data.data.forEach(item => {
                    item.imageScale = item.imageScale.split(",");
                    item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
                });
                this.setData({
                    productList: res.data.data
                });
            }

        });
    },
    //获取相关场所列表
    getPlaceList() {
        let that = this.data;
        activitiesPlace_list({ activityId: that.detailObj.id }).then(res => {
            if (!res.data.data || res.data.data.length === 0) {
                this.setData({
                    placeList: []
                });
            } else {
                res.data.data.forEach(item => {
                    item.imageScale = item.imageScale.split(",");
                    item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
                });
                this.setData({
                    placeList: res.data.data
                });
            }

        });
    },
    //获取相关景区列表
    getScenicspotList() {
        let that = this.data;
        activitiesScspot_list({ activityId: this.data.detailObj.id }).then(res => {
            if (!res.data.data || res.data.data.length === 0) {
                this.setData({
                    scenicspotList: []
                });
            } else {
                res.data.data.forEach(item => {
                    item.imageScale = item.imageScale.split(",");
                    item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
                });
                this.setData({
                    scenicspotList: res.data.data
                });
            }

        });
    },
    //活动点赞图标事件
    likeClick(e) {
        let that = this.data;
        let item = e.currentTarget.dataset.item;
        let flag = !item.likeState ? true : false;
        activityGive_option({ userId: that.user.id, activityId: item.id, state: flag }).then(res => {
            let state = "detailObj.likeState",
                index = "detailObj.likeNumber";
            if (res.data.code === 200) {
                wx.showToast({
                    icon: 'none',
                    title: res.data.msg,
                    duration: 2000,
                    mask:true
                })
                app.globalData.activityId = item.id;
                app.globalData.activityGive = flag ? 1 : 2; // 1是已点赞：2是取消点赞  
                app.globalData.activityGiveNum = !flag ? item.likeNumber - 1 : item.likeNumber + 1;
                //初始化活动收藏状态
                app.globalData.activityCtion = item.collectionState ? 1 : 2;
                app.globalData.activityCtionNum = item.collectionNumber
                this.setData({
                    [state]: flag,
                    [index]: !flag ? item.likeNumber - 1 : item.likeNumber + 1
                });
            };
        });
    },
    //收藏或取消收藏事件
    collectionClick(e) {
        let that = this.data,
            item = e.currentTarget.dataset.item,
            flag = !item.collectionState ? true : false;
        activityOption({ userId: that.user.id, activityId: item.id, state: flag }).then(res => {
            let state = "detailObj.collectionState",
                num = "detailObj.collectionNumber";
            if (res.data.code === 200) {
                wx.showToast({
                    icon: 'none',
                    title: res.data.msg,
                    duration: 2000,
                    mask:true
                });
                app.globalData.activityId = item.id;
                app.globalData.activityCtion = flag ? 1 : 2; // 1是已点赞：2是取消点赞 
                app.globalData.activityCtionNum = !flag ? item.collectionNumber - 1 : item.collectionNumber + 1
                //活动点赞初始化
                app.globalData.activityGive = item.likeState ? 1 : 2;
                app.globalData.activityGiveNum = item.likeNumber;
                this.setData({
                    [state]: flag,
                    [num]: !flag ? item.collectionNumber - 1 : item.collectionNumber + 1
                });
            };
        });
    },
    //拨打电话功能
    phoneClick(e) {
        let item = e.currentTarget.dataset.item;
        wx.makePhoneCall({
            phoneNumber: item,
            success: (res) => {
                console.log(res);
            },
            fail: (err) => {
                console.log(err);
            }
        })
    },
    /* 相关产品
       相关场所
       相关景区
       列表点击事件
    */
    relevant(e) {
        let item = e.currentTarget.dataset.item;
        let type = e.currentTarget.dataset.type;
        if (type === "商品") {
            wx.navigateTo({
                url: '/pagesShouYe/pages/commodityDetail/index?item=' + encodeURIComponent(JSON.stringify(item)),
            });
        } else if (type === "场所") {
            wx.navigateTo({
                url: '/pagesShouYe/pages/changsuoDetail/index?id=' + item.id,
            });
        } else if (type === "景区") {
            wx.navigateTo({
                url: '/pagesShouYe/pages/jingquDetail/index?id=' + item.id,
            });
        };
    },
    //获取导航栏信息
    getNavInfo() {
        this.setData({
            navHeight: app.globalData.navHeight, //导航栏高度
            navTop: app.globalData.navTop, //导航栏距顶部距离
            navObj: app.globalData.navObj, //胶囊的高度
            navWeight: app.globalData.navWeight, //胶囊宽度+距右距离
        });
        console.log(this.data.navTop, 'app');
    },
    //填写图标事件
    fillIn(e) {
        this.setData({
            soFlag: true
        });
    },
    //覆盖层收回事件
    layerFill(e) {
        this.setData({
            soFlag: false
        });
    },
    //报名按钮点击事件
    async sign(e) {
        let that = this.data;
        let item = e.currentTarget.dataset.item;
        if (item.activityState === 1) {
            if (item.signUpState) {
                wx.showModal({
                    title: '取消报名原因',
                    content: '',
                    editable: true,
                    success: (res) => {
                        if (res.confirm) {
                            if (!res.content) {
                                wx.showToast({
                                    icon: 'none',
                                    title: '请先填写取消报名原因',
                                    duration:2000,
                                    mask:true
                                });
                            } else {
                                //调用取消报名的接口
                                ActivityRegistration_quxiao({
                                    userId: that.user.id,
                                    activityId: that.detailObj.id,
                                    reason: res.content
                                }).then(res => {
                                    if (res.data.code === 200) {
                                        this.setData({
                                            "detailObj.peopleNumber": that.detailObj.peopleNumber - 1,
                                            "detailObj.signUpState": res.data.data
                                        });
                                        app.globalData.signUpNum = this.data.detailObj.peopleNumber;  //全局变量活动报名人数
                                        wx.showToast({
                                            icon: 'none',
                                            title: res.data.msg,
                                            duration:2000,
                                            mask:true
                                        })
                                    }
                                });
                            };
                        };
                    }
                })
            } else {
                wx.navigateTo({
                    url: '/pagesShouYe/pages/baomingXinxi/index?item=' + encodeURIComponent(JSON.stringify(item)),
                });
            };
        };
    },
    //获取评论列表
    async getList() {
        const _this = this.data;
        let res = await currentComment({ activityId: _this.detailObj.id });
        if (res.data.code === 200) {
            //评论数量
            app.globalData.activityId = _this.detailObj.id;
            app.globalData.activityMent = res.data.data.length;
            //评论收藏和点赞状态
            app.globalData.activityGive = _this.detailObj.likeState ? 1 : 2;
            app.globalData.activityGiveNum = _this.detailObj.likeNumber;
            app.globalData.activityCtion = _this.detailObj.collectionState ? 1 : 2;
            app.globalData.activityCtionNum = _this.detailObj.collectionNumber;

            this.setData({
                commentList: res.data.data,
            });
        };
    },
    //评论内容input框事件
    pinl(e) {
        const value = e.detail.value;
        this.setData({
            content: value
        });
    },
    //提交按钮事件
    async submit() {
        const _this = this.data;
        if (!_this.content) {
            wx.showToast({
                icon: "none",
                title: "请先输入评论内容",
                mask:true,
                duration:2000
            });
        } else {
            const obj = {
                userId: _this.user.id,
                activityId: Number(_this.detailObj.id),
                content: _this.content,
            };
            let res = await comment(obj);
            wx.showToast({
                icon: 'none',
                title: res.data.msg,
                duration: 2000,
                mask:true
            });
            this.getList();
            this.setData({
                content: "",
                "detailObj.commentNum": _this.detailObj.commentNum + 1,
            });
        };
    },
    //评论列表用户头像点击事件
    userTap(e) {
        let item = e.currentTarget.dataset.item;
        item.id = item.userId;
        if (item.userId === this.data.user.id) {
            wx.redirectTo({
                url: '/pages/index/index?index=' + 5,
            });
        } else {
            wx.navigateTo({
                url: '/pagesWoDe/pages/personalHomepage/index?item=' + encodeURIComponent(JSON.stringify(item)),
            });
        };
    },
    //地址图标点击事件
    addressTap(e) {
        let item = e.currentTarget.dataset.item;
        wx.openLocation({
            latitude: Number(item.latitude),
            longitude: Number(item.longitude),
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(res) {
        let that = this;
        return {
            title: that.data.detailObj.title,
            // imageUrl: that.data.detailObj[0],
            path: "pagesShouYe/pages/bnnerDetailMore/index?id=" + that.data.detailObj.id + "&sheet=" + true,
            success: function (res) {
                console.log(res, "转发成功")
            },
            fail: function (res) {
                console.log(res, "转发失败")
            }
        }
    },
})